/**
 * 
 */
package org.gbif.crawler.console.servlet.tail;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author tim
 */
public class LinkDecorator implements Decorator {
  /**
   * Starts with a word boundary and protocol identifier,
   * don't include any whitespace, '&lt;', nor '>'.
   * In addition, the last character shouldn't be ',' ':', '"', etc, as often those things show up right next
   * to URL in plain text (e.g., test="http://www.example.com/")
   */
  private static final Pattern URL = Pattern.compile("\\b(http|https|ftp)://[^\\s<>]+[^\\s<>,\\.:\"'()\\[\\]=]");
  
  @Override
  public String decorate(String line) {
    Matcher m = URL.matcher(line);

    StringBuffer sb = new StringBuffer();
    while (m.find()) {
      String replacement = "<a href='" +m.group() +"'>" + m.group() + "</a>";
      m.appendReplacement(sb, replacement);
    }
    m.appendTail(sb);    
    return sb.toString();
  }
}
